import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { useUserStore } from '@/store/modules/user';
import { useSystemStore } from '@/store/modules/system';
console.log(import.meta.env.VITE_APP_BASE_API)

// 创建 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_APP_PYTHON_API,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		const userStore = useUserStore();
		if (userStore.token) {
			config.headers["token"] = userStore.token;
		}
		return config;
	},
	(error: any) => {
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		const system = useSystemStore();
		const { code, msg } = response.data;
		if (code === 200 || code === '200' || code < 207) {
			return response.data;
		}
		// 响应数据为二进制流处理(Excel导出)
		if (response.data instanceof ArrayBuffer) {
			return response;
		}
		if(system.isCurrenDel == true){
			ElMessage.error('已删除正在生成的对话！');
		}else{
			console.log('7777777777777777',msg)
			ElMessage.error(msg || '系统出错');
		}
		if(msg == 'token不正确' || msg == '用户信息异常' || msg == '参数信息丢失'){
			localStorage.clear();
			location.reload();
		}
		return Promise.reject(new Error(msg || 'Error'));
	},
	(error: any) => {
		if (error.response.data) {
			const { code, msg } = error.response.data;
			// token 过期,重新登录
			if (code === 'A0230') {
				ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
					confirmButtonText: '确定',
					type: 'warning'
				}).then(() => {
					localStorage.clear();
					window.location.href = '/';
				});
			} else {  
				const system = useSystemStore();
				if(system.isFour == true){
					console.log('接口报错88888888888888',msg)

					system.isFour = false;
				}else{
					console.log('接口报错999999999999',msg)

					ElMessage.error(msg || '系统出错');
				}
			}
		}
		return Promise.reject(error.message);
	}
);

// 导出 axios 实例
export default service;
